import { Request, Response } from "express";
import { NextFunction } from "express-serve-static-core";
const express = require("express");
const router = express.Router();
import * as config from "../../config";
import big from "../../big";

import r from "../r";

router.post(
  "/addOrder",
  async (req: Request, res: Response, next: NextFunction) => {
    const { price, uid, zi, mu, type, amount } = req.body;
    if (process.env.NODE_ENV === "eh") {
      res.json({
        code: 200,
        data: undefined,
        msg: "success"
      });
    }
    const newurl = `${config.api}/order/takeOrder`;
    const [num2symbol, symbol2num] = await config.selectSymbolConfig();
    try {
      const ret = await r(
        {
          url: newurl,
          body: JSON.stringify({
            userId: uid,
            baseId: symbol2num[zi],
            counterId: symbol2num[mu],
            price: Number(price),
            amount: Number(amount),
            side: type === "buy" ? 1 : 0 // bid => 1 | ask => 0
          })
        },
        req,
        res
      );
      const jsonRet = JSON.parse(ret.body);

      res.json(jsonRet);
    } catch (e) {
      res.json({
        code: -1,
        data: undefined,
        msg: e
      });
    }
  }
);

router.post(
  "/delOrder",
  async (req: Request, res: Response, next: NextFunction) => {
    const { id } = req.body;
    if (process.env.NODE_ENV === "eh") {
      res.json({
        code: 200,
        data: undefined,
        msg: "success"
      });
    }
    try {
      const newurl = `${config.api}/order/cancelOrder/${id}`;

      const ret = await r(
        {
          method: "GET",
          url: newurl
        },
        req,
        res
      );
      const jsonRet = JSON.parse(ret.body);

      res.json(jsonRet);
    } catch (e) {
      res.json({
        code: -1,
        data: undefined,
        msg: e
      });
    }
  }
);

router.get(
  "/selectHistory",
  async (req: Request, res: Response, next: NextFunction) => {
    const { uid, zi, mu, type } = req.query;
    if (process.env.NODE_ENV === "eh") {
      const data = [
        {
          id: "sdlkfj",
          time: 1544065401,
          zi: "BCH",
          mu: "BTC",
          type: "buy",
          price: "0.333333",
          amount: "333.333",
          used: "222.3333",
          tab: "active"
        },
        {
          id: "sdlkfj",
          time: 1544065401,
          zi: "BCH",
          mu: "BTC",
          type: "sell",
          price: "0.333333",
          amount: "333.333",
          used: "222.3333",
          tab: "active"
        },
        {
          id: "sdlkfj",
          time: 1544065401,
          zi: "BCH",
          mu: "BTC",
          type: "buy",
          price: "0.333333",
          amount: "333.333",
          used: "222.3333",
          tab: "history"
        },
        {
          id: "sdlkfj",
          time: 1544065401,
          zi: "BCH",
          mu: "BTC",
          type: "sell",
          price: "0.333333",
          amount: "333.333",
          used: "222.3333",
          tab: "history"
        }
      ];
      res.json({
        code: 200,
        data: undefined,
        msg: "success",
        total: 0
      });
    }
    try {
      const { zi, mu, p, size } = req.query;
      // pageNum  pageSize
      const history = await r(
        {
          method: "GET",
          url: `${config.api}/order/${zi}_${mu}/history?pageNum=${Number(
            p
          )}&pageSize=${size}`
        },
        req,
        res
      );

      const [num2symbol, symbol2num] = await config.selectSymbolConfig();

      const jsonRetHistory = JSON.parse(history.body);

      let jsonRet: any = {
        code: 200,
        data: [],
        msg: "success"
      };

      if (jsonRetHistory && jsonRetHistory.data.list) {
        jsonRetHistory.data.list = jsonRetHistory.data.list
          .slice()
          .map((d: any) => {
            return {
              ...d,
              tab: "history"
            };
          });

        jsonRet.data = jsonRetHistory.data.list;

        jsonRet.total = jsonRetHistory.data.total;
      }

      if (jsonRet && jsonRet.data) {
        jsonRet.data = jsonRet.data.slice().map((d: any) => {
          const zi = num2symbol[d.baseId];
          const mu = num2symbol[d.counterId];
          return {
            id: d.id,
            time: d.createtime,
            endTime: d.endtime,
            zi,
            mu,
            type: Number(d.side) === 1 ? "buy" : "sell",
            price: big.toFixed(d.price, config.point),
            amount: big.toFixed(d.amount, config.point),
            used: big.toFixed(
              big.minus(
                big.toFixed(d.amount, config.point),
                big.toFixed(d.last, config.point)
              ),
              config.point
            ),
            tab: d.tab
          };
        });
      }

      res.json(jsonRet);
    } catch (e) {
      res.json({
        code: -1,
        data: undefined,
        msg: e
      });
    }
  }
);

router.get(
  "/selectActive",
  async (req: Request, res: Response, next: NextFunction) => {
    const { uid, zi, mu, type } = req.query;
    if (process.env.NODE_ENV === "eh") {
      const data = [
        {
          id: "sdlkfj",
          time: 1544065401,
          zi: "BCH",
          mu: "BTC",
          type: "buy",
          price: "0.333333",
          amount: "333.333",
          used: "222.3333",
          tab: "active"
        },
        {
          id: "sdlkfj",
          time: 1544065401,
          zi: "BCH",
          mu: "BTC",
          type: "sell",
          price: "0.333333",
          amount: "333.333",
          used: "222.3333",
          tab: "active"
        },
        {
          id: "sdlkfj",
          time: 1544065401,
          zi: "BCH",
          mu: "BTC",
          type: "buy",
          price: "0.333333",
          amount: "333.333",
          used: "222.3333",
          tab: "history"
        },
        {
          id: "sdlkfj",
          time: 1544065401,
          zi: "BCH",
          mu: "BTC",
          type: "sell",
          price: "0.333333",
          amount: "333.333",
          used: "222.3333",
          tab: "history"
        }
      ];
      res.json({
        code: 200,
        data: undefined,
        msg: "success"
      });
    }
    try {
      const { zi, mu, p, size } = req.query;

      const active = await r(
        {
          method: "GET",
          url: `${config.api}/order/${zi}_${mu}/on?pageNum=${Number(
            p
          )}&pageSize=${size}`
        },
        req,
        res
      );

      const [num2symbol, symbol2num] = await config.selectSymbolConfig();

      const jsonRetActive = JSON.parse(active.body);

      let jsonRet: any = {
        code: 200,
        data: [],
        msg: "success",
        total: 0
      };

      if (jsonRetActive && jsonRetActive.data.list) {
        jsonRetActive.data.list = jsonRetActive.data.list
          .slice()
          .map((d: any) => {
            return {
              ...d,
              tab: "active"
            };
          });

        jsonRet.data = jsonRetActive.data.list;

        jsonRet.total = jsonRetActive.data.total;
      }
      if (jsonRet && jsonRet.data) {
        jsonRet.data = jsonRet.data.slice().map((d: any) => {
          const zi = num2symbol[d.baseId];
          const mu = num2symbol[d.counterId];
          return {
            id: d.id,
            time: d.createtime,
            endTime: d.endtime,
            zi,
            mu,
            type: Number(d.side) === 1 ? "buy" : "sell",
            price: big.toFixed(d.price, config.point),
            amount: big.toFixed(d.amount, config.point),
            used: big.toFixed(
              big.minus(
                big.toFixed(d.amount, config.point),
                big.toFixed(d.last, config.point)
              ),
              config.point
            ),
            tab: d.tab
          };
        });
      }

      res.json(jsonRet);
    } catch (e) {
      res.json({
        code: -1,
        data: undefined,
        msg: e
      });
    }
  }
);

export default router;
